<template>
  <view class="container">
    <!-- 书架标题栏 -->
    <uni-section class="mb-10" title="书架" titleFontSize="16">
      <template v-slot:right>
        <view class="ai-tag" @click="navigateToAI">
          AI 智慧阅读
        </view>
      </template>
    </uni-section>

    <!-- 书架列表 -->
    <view class="book-list">
      <view v-for="item in bookList" :key="item.id" class="book-item-wrapper"
        :class="{'selected': isSelected && item.isSelected}" @touchstart="onTouchStart(item)" @touchend="onTouchEnd"
        @click="handleBookClick(item)">
        <checkbox v-if="isSelected" class="book-checkbox" :checked="item.isSelected"
          @click.stop="toggleBookSelection(item)" />
        <view class="book-item">
          <image class="book-image" :src="item.cover" mode="aspectFill"></image>
          <view class="book-name">{{item.title}}</view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar" v-if="isSelected">
      <view class="action-item" @tap="handleFinish">
        <uni-icons type="undo" size="24"></uni-icons>
        <text>返回</text>
      </view>
      <view class="action-item" @tap="toggleSelectAll">
        <uni-icons :type="isAllSelected ? 'checkbox-filled' : 'checkbox'" size="24"></uni-icons>
        <text>{{isAllSelected ? '取消全选' : '全选'}}</text>
      </view>
      <view class="action-item" @tap="handleShare">
        <uni-icons type="paperplane" size="24"></uni-icons>
        <text>分享</text>
      </view>
      <view class="action-item delete" @tap="handleDelete">
        <uni-icons type="trash" size="24"></uni-icons>
        <text>删除</text>
        <text v-if="selectedCount > 0" class="badge">{{selectedCount}}</text>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'

  export default {
    computed: {
      ...mapState('m_book', ['bookList']),
      selectedCount() {
        return this.bookList.filter(book => book.isSelected).length
      },
      isAllSelected() {
        return this.bookList.length > 0 && this.bookList.every(book => book.isSelected)
      }
    },
    data() {
      return {
        isSelected: false,
        pressTimer: null,
        longPressTriggered: false
      }
    },
    methods: {
      ...mapMutations('m_book', ['selectAllBooks', 'cancelSelectAllBooks', 'removeBookByIds']),

      // 新增本地方法处理书籍选择状态
      toggleBookSelection(item) {
        this.$set(item, 'isSelected', !item.isSelected)
      },

      onTouchStart(item) {
        this.longPressTriggered = false
        this.pressTimer = setTimeout(() => {
          this.longPressTriggered = true
          this.enterSelectionMode(item)
        }, 600)
      },

      onTouchEnd() {
        clearTimeout(this.pressTimer)
        this.pressTimer = null
      },

      enterSelectionMode(item) {
        uni.hideTabBar()
        this.isSelected = true
        this.$set(item, 'isSelected', true)
      },

      handleBookClick(item) {
        if (this.longPressTriggered) {
          this.longPressTriggered = false
          return
        }

        if (this.isSelected) {
          this.toggleBookSelection(item)
          return
        }

        this.navigateToBookDetail(item)
      },

      navigateToBookDetail(item) {
        uni.navigateTo({
          url: `/subpkg/view/view?data=${encodeURIComponent(JSON.stringify({
          id: item.id,
          title: item.title,
          src: item.cover
        }))}`
        })
      },

      navigateToAI() {
        uni.navigateTo({
          url: '/subpkg/ai/ai'
        })
      },

      toggleSelectAll() {
        if (this.isAllSelected) {
          this.cancelSelectAllBooks()
        } else {
          this.selectAllBooks()
        }
      },

      // 修改后的删除处理逻辑
      async handleDelete() {
        const selectedIds = this.bookList
          .filter(book => book.isSelected)
          .map(book => book.id);

        if (selectedIds.length === 0) {
          uni.showToast({
            title: '请选择要删除的书籍',
            icon: 'none'
          });
          return;
        }

        try {
          const [err, succ] = await uni.showModal({
            title: '提示',
            content: `确定要删除选中的${selectedIds.length}本书籍吗？`
          });
          // 检查用户是否点击了确定
          if (!succ || !succ.confirm) return;
          // 显示加载状态
          uni.showLoading({
            title: '删除中...',
            mask: true
          });

          // 发送删除请求
          const {
            data
          } = await uni.$http.delete(`/book/delete?ids=${selectedIds.join(',')}`);

          // 隐藏加载状态
          uni.hideLoading();

          // 检查返回状态码
          if (data.code !== 1) {
            throw new Error(data.message || '删除失败');
          }

          // 更新本地状态
          this.removeBookByIds(selectedIds);
          uni.$showMsg('删除成功');

          // 如果删完了所有书，退出选择模式
          if (this.bookList.length === 0) {
            this.handleFinish();
          }
        } catch (error) {
          uni.hideLoading();
          console.error('删除失败:', error);
          uni.$showMsg(error.message || '删除操作失败');
        }
      },
      handleShare() {
        const selectedBooks = this.bookList.filter(book => book.isSelected)
        if (selectedBooks.length === 0) {
          uni.showToast({
            title: '请选择要分享的书籍',
            icon: 'none'
          })
          return
        }

        uni.showActionSheet({
          itemList: ['分享给好友', '分享到朋友圈'],
          success: (res) => {
            console.log('分享方式:', res.tapIndex)
          }
        })
      },

      handleFinish() {
        this.isSelected = false
        uni.showTabBar()
        this.cancelSelectAllBooks()
      }
    }
  }
</script>
<style lang="scss">
  .container {
    padding-bottom: 100rpx; // 为底部操作栏留出空间
  }

  .ai-tag {
    margin-left: auto;
    color: #ff4d4f;
    border: 1px solid #ff4d4f;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    background-color: #fff2f0;

    &:active {
      opacity: 0.8;
    }
  }

  .book-list {
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;
  }

  .book-item-wrapper {
    position: relative;
    width: 33.33%;
    padding: 20rpx;
    box-sizing: border-box;
    transition: all 0.2s ease;

    &.selected {
      background-color: #e6f7ff;
      border-radius: 12rpx;
    }
  }

  .book-checkbox {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    z-index: 10;
  }

  .book-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .book-image {
      width: 180rpx;
      height: 240rpx;
      border-radius: 8rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      margin-bottom: 16rpx;
    }

    .book-name {
      width: 180rpx;
      font-size: 28rpx;
      color: #333;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
    z-index: 100;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      color: #666;
      position: relative;

      &.delete {
        color: #ff4d4f;
      }

      .badge {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        background-color: #ff4d4f;
        color: white;
        border-radius: 50%;
        width: 36rpx;
        height: 36rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20rpx;
      }
    }
  }
</style>
